import React, {CSSProperties, ReactComponentElement} from 'react'
import BScroll,{PullDownRefresh,PullUpLoad} from 'better-scroll'
import PubSub from 'pubsub-js'
import debounce from "../../utils/debounce";
BScroll.use(PullDownRefresh)
BScroll.use(PullUpLoad)

interface IProps {
    style: CSSProperties;
    content: ReactComponentElement<any>;
}
const Scroll = React.forwardRef((props: IProps,ref) => {
    const [myScroll,setScroll] = React.useState<any>()

    //通过useImperativeHandle-hook 向父容器返回方法
    React.useImperativeHandle(ref,() => {
        return {
            name: 'bs-scroll',
            scrollRefresh, //刷新组件高度
            endPullUp, //结束触底事件
            endPullDown, //结束上拉事件
        }
    })

    //组件挂载时初始化scroll
    React.useEffect(() => {
        const wrapper = (document.querySelector('.wrapper') as HTMLElement)
        const bs = new BScroll(wrapper,{
            click: true,
            scrollY: true,
            pullUpLoad: true,
            pullDownRefresh: true,
            disableTouch: false
        })
        setScroll(bs)
        //监听页面刷新滚动事件,并增加防抖
        PubSub.subscribe('rfs',debounce((_: string,data: any) => {
            bs.refresh() //刷新滚动高度
        },500))
        //监听页面滚动位置
        bs.on('scroll',(pos: any) => {
            PubSub.publish('pos',pos)
        })
        //监听触底上拉,调用父组件传递的函数
        bs.on('pullingUp',() => {
            PubSub.publish('onBottom')
        })
        bs.on('pullingDown',() => {
            PubSub.publish('onTop')
        })
        return () => {
            PubSub.clearAllSubscriptions()
        }
    }, []) // eslint-disable-line react-hooks/exhaustive-deps

    //刷新容器高度
    const scrollRefresh = () => {
        myScroll.refresh()
    }
    //结束触底事件
    const endPullUp = () => {
        myScroll.finishPullUp()
    }

    const endPullDown = () => {
        myScroll.finishPullDown()
    }
    return (
        <div className='wrapper' style={props.style}>
            <div className='content'>
                {
                    props.content
                }
            </div>
        </div>
    )
})

export default Scroll